import 'dart:io';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_function.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_color.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_jiami.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_widget.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:photo_view/photo_view.dart';
/*
其他:
https://pub-web.flutter-io.cn/packages/lottie


 */

abstract class XImageUtils{


  /*
  图片压缩:
  https://pub-web.flutter-io.cn/packages/flutter_image_compress
  dependencies:
    flutter_image_compress: <latest_version>
  import 'package:flutter_image_compress/flutter_image_compress.dart';
   */
  static Future<Uint8List?> compressFileImageToUint8List(
      {
        required String filePath,
        int minWidth=500,
        int minHeight=500,
        int quality=80,
      }
      ) async{
    File file=File(filePath);
    if(file.existsSync()){
      Uint8List? result = await FlutterImageCompress.compressWithFile(
        filePath,
        minWidth: minWidth,
        minHeight: minHeight,
        quality: quality,
      );
      return result;
    }

    return null;
  }

  static Future<String?> compressFileImageToNewFilePath(
      {
        required String filePath,
        required String targetPath,
        int minWidth=500,
        int minHeight=500,
        int quality=80,
      }
      ) async{
    File file=File(filePath);
    //file.readAsBytes()

    if(file.existsSync()){
      XFile? result = await FlutterImageCompress.compressAndGetFile(
        filePath,
        targetPath,
        minWidth: minWidth,
        minHeight: minHeight,
        quality: quality,
      );

      //result.readAsBytes();
      return result?.path;
    }

    return null;
  }


  /*
  显示图片,支持放大缩小
  图片浏览:
  https://pub.flutter-io.cn/packages/photo_view
  dependencies:
    photo_view: ^0.15.0
  import 'package:photo_view/photo_view.dart';
   */
  static Widget getPhotoViewWithAsset(
      String assetImageName, //'welcome_app.png'
          {
        Color? backgroundColor=XColorUtils.colorF8F8F8,
      }
      ){
    return PhotoView(
        backgroundDecoration:backgroundColor==null?null:XWidgetUtils.getBoxDecoration(
          backgroundColor: backgroundColor,
        ),
        imageProvider: AssetImage('assets/images/$assetImageName')
    );
  }
  static Widget getPhotoViewWithUrl(
      String imageUrl,
      {
        Color? backgroundColor=XColorUtils.colorF8F8F8,
      }
      ){
    return PhotoView(
        backgroundDecoration:backgroundColor==null?null:XWidgetUtils.getBoxDecoration(
          backgroundColor: backgroundColor,
        ),
        imageProvider: CachedNetworkImageProvider(imageUrl)
    );
  }
  static Widget getPhotoViewWithFile(
      String imageFilePath,
      {
        Color? backgroundColor=XColorUtils.colorF8F8F8, //PhotoView默认是黑色
      }
      ){
    return PhotoView(
        backgroundDecoration:backgroundColor==null?null:XWidgetUtils.getBoxDecoration(
          backgroundColor: backgroundColor,
        ),
        imageProvider:  FileImage(File(imageFilePath), scale: 1)
    );
  }

  /*
  加载svg图片:
  https://pub-web.flutter-io.cn/packages/flutter_svg/install
  dependencies:
    flutter_svg: ^2.0.10+1
  import 'package:flutter_svg/flutter_svg.dart';

  其他: https://pub-web.flutter-io.cn/packages/flutter_svg_provider

   */
  static Widget getSVGWidgetWithAsset(
      String assetSVGName, //'welcome_app.svg'
          {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,
      }
      ){
    return SvgPicture.asset(
      'assets/images/$assetSVGName',
      fit: fit,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width,
      height: height,
      colorFilter: color==null?null:ColorFilter.mode(color, BlendMode.srcIn),
    );

  }
  static Widget getSVGWidgetWithUrl(
      String url,
      {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,
      }
      ){
    return SvgPicture.network(
      url,
      fit: fit,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width,
      height: height,
      colorFilter: color==null?null:ColorFilter.mode(color, BlendMode.srcIn),
      placeholderBuilder: (BuildContext context) => Container(
          padding: const EdgeInsets.all(30.0),
          child: const CircularProgressIndicator()),
    );

  }

  //String rawSvg = '''<svg ...>...</svg>''';
//   static Widget getSVGWidgetWithCode(
//       String rawSvg,
//       {
//         required int width,
//         required int height,
//         Color? color,
//         BoxFit fit=BoxFit.cover,
//       }
//       ) async{
//
//     final String rawSvg = '''<svg ...>...</svg>''';
//     final PictureInfo pictureInfo = await vg.loadPicture(SvgStringLoader(rawSvg), null);
//
// // You can draw the picture to a canvas:
//     //canvas.drawPicture(pictureInfo.picture);
//
// // Or convert the picture to an image:
//     final ui.Image image = await pictureInfo.picture.toImage(width,height);
//
//     pictureInfo.picture.dispose();
//
//     return image;
//
//   }

  /*
  (支持圆角或圆形)图片加载(网络,缓存): https://pub.dev/packages/cached_network_image
  依赖:
  dependencies:
    cached_network_image: ^3.3.1
  引入:
  import 'package:cached_network_image/cached_network_image.dart';


  CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     )

    CachedNetworkImage(
  imageUrl: "http://via.placeholder.com/200x150",
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
          colorFilter:
              ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
    ),
  ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
)

 */

  static Widget getImageWidgetWithUrl(
      {
        Color? backgroundColor,
        double borderWidth=1,
        required double width,
        required double height,
        required String imageUrl,
        required String defaultImageAssetName,
        double radius=5,//圆角半径
        bool isCircle=false,// false为矩形, true为圆形
      }
      ){

    //加载网络图片,支持gif动画,没有占位图功能,加载完后,直接显示
    //return Image.network(url);
    //return Image(image: CachedNetworkImageProvider(imageUrl));

    // return CachedNetworkImage(
    //   imageUrl: imageUrl,
    //   placeholder: (context, url) => getImageWidgetWithAsset(defaultImageAssetName),
    //   errorWidget: (context, url, error) => getImageWidgetWithAsset(defaultImageAssetName),
    //   imageBuilder: (
    //       BuildContext context,
    //       ImageProvider imageProvider,
    //       ){
    //   },
    // );

    return XWidgetUtils.getLayoutContainer(
        padding: XWidgetUtils.getEdgeInsets(borderWidth, borderWidth, borderWidth, borderWidth),
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
          shape:isCircle?BoxShape.circle:BoxShape.rectangle,
        ),
        child: CachedNetworkImage(
          width: width-borderWidth,
          height: height-borderWidth,
          imageUrl: imageUrl,
          imageBuilder: (
              BuildContext context,
              ImageProvider imageProvider){
            return XWidgetUtils.getLayoutContainer(
                decoration: BoxDecoration(
                    borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
                    shape:isCircle?BoxShape.circle:BoxShape.rectangle,
                    image: DecorationImage(
                      image: imageProvider,
                      fit: BoxFit.cover,
                    )
                )
            );
          },
          placeholder: (context, url) => XWidgetUtils.getLayoutContainer(
              decoration: BoxDecoration(
                  borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
                  shape:isCircle?BoxShape.circle:BoxShape.rectangle,
                  image: DecorationImage(
                    image: AssetImage('assets/images/$defaultImageAssetName'),
                    fit: BoxFit.cover,
                    //colorFilter:ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
                  )
              )
          ),
          errorWidget: (context, url, error) => XWidgetUtils.getLayoutContainer(
              decoration: BoxDecoration(
                  borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
                  shape:isCircle?BoxShape.circle:BoxShape.rectangle,
                  image: DecorationImage(
                    image: AssetImage('assets/images/$defaultImageAssetName'),
                    fit: BoxFit.cover,
                    //colorFilter:ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
                  )
              )
          ),
        )
    );
  }




  /*
  本地图片素材
在pubspec.yaml添加图片路径,如:
flutter:
  assets:
    # Add assets from the images directory to the application.
    - assets/images/

XImageUtils.getImageWidgetWithAsset(
          'welcome_app.png',
          width: 122,
          height: 32.5
      )
   */
  static Image getImageWidgetWithAsset(
      String assetImageName, //'welcome_app.png'
          {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,
      }
      ){
    return Image.asset(
      'assets/images/$assetImageName',
      fit: fit,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width,
      height: height,
      color: color,
    );

  }

  /*
  加载外储存卡(硬盘)图片
   */
  static Image getImageWidgetWithFile(
      String imageFilePath,
      {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      }
      ){
    return Image.file(
      File(imageFilePath),
      fit: fit,
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width,
      height: height,
      color: color,
    );

  }



  static Image getImageWithBase64(String base64Str){
    Uint8List imageBytes = XJiamiUtils.base64ToUint8List(base64Str);
    return Image.memory(imageBytes);
  }


  //获得宽和高
  static void getImageInfo(
      {
        Uint8List? imageBytes,
        String? base64Str,
        required XFunctionResultCallback<Map<String,dynamic>> callback,
      }
      ){

    if(imageBytes==null){
      if(base64Str!=null){
        imageBytes = XJiamiUtils.base64ToUint8List(base64Str);
      }
    }

    if(imageBytes!=null){
      MemoryImage memoryImage=MemoryImage(imageBytes);
      memoryImage.resolve(ImageConfiguration()).addListener(ImageStreamListener(
              (info,_){
            Map<String,dynamic> res={};
            res['width']=info.image.width;
            res['height']=info.image.height;
            callback(res);
          }
      ));
    }else{
      Map<String,dynamic> res={};
      res['width']=0;
      res['height']=0;
      callback(res);
    }

  }

  //Icon////////////////////////////////////////////////////////////////////

  /*
  DecorationImage(//设置图片背景，设置image需要一个DecorationImage类
                // Load image from assets
                  image: AssetImage('images/base_widgets/icon_main_date_select@2x.png'),
                  // Make the image cover the whole area
                  fit: BoxFit.cover))
   */


  //本地系统自带图标素材 Icons.directions_car Icons.directions_bus,...
  //icon: Icon(Icons.home, color: _BottomNavigationColor,size:36),
  //IconButton
  static Icon getIconWidget(
      {
        required IconData Icons_icon,
        Color? color,
        double? size,
      }

      ){

    return Icon(
      Icons_icon,
      color: color,
      size: size,
    );
  }


  static ImageIcon getImageIconWidget(
      String assetImageName, //'welcome_app.png',
          {
        Color? color,
        double? size,
      }

      ){

    return ImageIcon(
      AssetImage('assets/images/$assetImageName',),
      color: color,
      size: size,
    );
  }



//获得图片像素点颜色(注意:这里Image并非widget的image)
//https://www.jianshu.com/p/ffb4b58f0aa9/
//https://www.learnfk.com/question/flutter/71197408.html

// static Future<Color> getPixelColors(ui.Image img) async {
//   ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);
//   Codec codec = await ui.instantiateImageCodec(byteData!.buffer.asUint8List());
//   FrameInfo frame = await codec.getNextFrame();
//   ByteData? byteData2 = await frame.image.toByteData(format: ui.ImageByteFormat.png);
//   var color = byteData2.getPixel(100, 100);
//   print(color);
//   return color;
// }



//////////////////////////


}
